#include <cstdio>
#include <iostream>
#include <string>

extern "C" {
#include <libavformat/avformat.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_timer.h>
}

#include "ThreadSafeQueue.h"
#include "Demuxer.h"
#include "Decoder.h"
#include "Render.h"


int main(int argc, char* argv[]) {
    if (argc < 2) {
        std::cerr << "Usage: " << argv[0] << " <input file>" << std::endl;
        return 1;
    }

    const std::string input_filename = argv[1];

    // 设置队列容量
    const size_t packet_queue_capacity = 100;
    const size_t frame_queue_capacity = 100;

    ThreadSafeQueue<AVPacket*> packet_queue(packet_queue_capacity);
    ThreadSafeQueue<AVFrame*> frame_queue(frame_queue_capacity);

    std::atomic<bool> demux_done(false);
    Demuxer demuxer(input_filename, packet_queue, demux_done);
    if (!demuxer.init()) {
        std::cerr << "Failed to initialize demuxer." << std::endl;
        return 1;
    }

    std::atomic<bool> decode_done(false);
    Decoder decoder(packet_queue, frame_queue, demux_done, decode_done);
    if (!decoder.init(demuxer.get_codec_paras())) {
        std::cerr << "Failed to initialize decoder." << std::endl;
        return 1;
    }

    // 获取视频帧率
    const AVStream* vs = demuxer.get_video_stream();
    double frame_rate = av_q2d(vs->avg_frame_rate);

    std::atomic<bool> render_done(false);
    Renderer renderer(frame_queue, decode_done, render_done);
    if (!renderer.init(demuxer.get_width(), demuxer.get_height(), frame_rate)) {
        std::cerr << "Failed to initialize renderer." << std::endl;
        return 1;
    }

    // 启动所有线程
    demuxer.start();
    decoder.start();
    renderer.start();

    // 处理用户输入事件
    SDL_Event event;
    bool quit = false;
    while (!quit) {
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT || render_done) {
                quit = true;
                std::printf("Quit\n");
                std::fflush(stdout);
                break;
            } else if (event.type == SDL_KEYDOWN) {
                if (event.key.keysym.sym == SDLK_SPACE) {
                    renderer.toggle_pause();
                }
            }
        }
        SDL_Delay(10);
    }

    // 停止所有线程
    demuxer.stop();
    decoder.stop();
    renderer.stop();

    return 0;
}